﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using TTQT.TTQT_Code;

public partial class DanhMuc_DMAnChi : System.Web.UI.UserControl
{
    override protected void OnInit(EventArgs e)
    {
        //
        // CODEGEN: This call is required by the ASP.NET Web Form Designer.
        //
        InitializeComponent();
        base.OnInit(e);
    }
    private void InitializeComponent()
    {

    }
    protected void Page_Load(object sender, EventArgs e)
    {
        //if(isRole("ksv"))
        //{
        //    cmdAddNew.Visible = false;
        //}
        lblError.Text = string.Empty;
        if (!Page.IsPostBack)
        {
            visiblePanels(true, false);
            cboDotPhatHanh.DataBind();
            datagrid.DataBind();
            //cboDotPhatHanh.Items.Add(new ListItem("Tất cả các đợt","-1"));
        }
    }
    private void bindGrid()
    {
        try
        {
            ds.SelectCommandType = SqlDataSourceCommandType.Text;
            ds.SelectCommand = "SELECT ma,MaLoaiAnChi1=MaLoaiAnChi,MaLoaiAnChi=case MaLoaiAnChi when 1 then N'Ấn chỉ thường' else N'Ấn chỉ quan trọng' end,MaAnChi,TenAnChi,AnChiMau, DonGia, Ma_DonGia from MaAnChi";
            DataTable tb = ((DataView)ds.Select(System.Web.UI.DataSourceSelectArguments.Empty)).ToTable();
            datagrid.DataSource = tb;
            datagrid.DataBind();
        }
        catch (Exception)
        {
        }
    }
    private void visiblePanels(bool visibleGrid, bool visibleEdit)
    {
        this.pnGroupGrid.Visible = visibleGrid;
        this.pnEdit.Visible = visibleEdit;
    }
    protected void cmdAddNew_Click(object sender, EventArgs e)
    {
        lblError.Text = "";
        txtId.Text = "";
        lblUpdateStatus.Text = "";
        visiblePanels(false, true);
        this.txtTenAnChi.Text = string.Empty;
    }

    protected void cmdUpdate_Click(object sender, EventArgs e)
    {
        if(cboDotPhatHanh_edit.SelectedValue.Equals("-1"))
        {
            MyWebUtils.MyWebUtil.alert(this.Page,"De nghi chon lai dot phat hanh!");
            return;
        }
        try
        {
            // Nếu là sửa Thì ID sẽ khác rỗng
            if (txtId.Text != "")
            {
                int anChiMau = (cbAnChiMau.Checked == true) ? 1 : 0;
                int xuatKH = (chkXuatKH.Checked == true) ? 1 : 0;
                ds.UpdateCommand = "UPDATE MaAnChi"
                                   + " SET "
                                   + " MaLoaiAnChi ='" + ddlMaLoaiAnChi.SelectedValue.ToString()
                                   + "', MaAnChi =N'" + txtMaAnChi.Text.Trim()
                                   + "', TenAnChi =N'" + txtTenAnChi.Text.Trim()
                                   + "', TenNhom =N'" + txtTenNhom.Text.Trim()
                                   + "', AnChiMau ='" + anChiMau
                                   + "', XuatKHTrongQLAC='" + xuatKH
                                   + "', DonGia ='" + txtDonGia.Text
                                   + "', MaDotPhatHanh ='" + cboDotPhatHanh_edit.SelectedValue
                                   + "', Ma_DonGia ='"
                                   + "', DonViTinh =N'"+cboDonViTinh.SelectedValue
                                   + "', LoaiTien='" + cboLoaiTien.SelectedValue
                                   + "' WHERE Ma=" + txtId.Text.Trim()
                    ;
                ds.Update();
                datagrid.DataBind();
                visiblePanels(true, false);
            }
            // Nếu là thêm mới thì ID sẽ rỗng
            else
            {
                int anChiMau = (cbAnChiMau.Checked == true) ? 1 : 0;
                ds.InsertCommand = "INSERT INTO MaAnChi (MaLoaiAnChi,MaAnChi, TenAnChi,TenNhom, AnChiMau, DonGia,Ma_DonGia,MaDotPhatHanh,DonViTinh,LoaiTien) "
                                   + " VALUES( '" + ddlMaLoaiAnChi.SelectedValue.ToString()
                                   + "', N'" + txtMaAnChi.Text.Trim()
                                   + "', N'" + txtTenAnChi.Text.Trim()
                                   + "', N'" + txtTenNhom.Text.Trim()
                                   + "', '" + anChiMau
                                   + "', '" + txtDonGia.Text.Trim()
                                   + "', '"
                                   + "', '" + cboDotPhatHanh_edit.SelectedValue
                                   + "',N'" + cboDonViTinh.SelectedValue
                                   + "',N'" + cboLoaiTien.SelectedValue
                                   + "') ";
                ds.Insert();
                datagrid.DataBind();
                visiblePanels(true, false);
            }
        }
        catch (Exception ex)
        {
            lblUpdateStatus.Attributes.Add("style", "color:red;font-weight:bold;");
            this.lblUpdateStatus.Text = "Loi khi cap nhat. Nhap lai! <br />" + e.ToString();
            //Log methods here
        }
    }
    protected void cmdCancel_Click(object sender, EventArgs e)
    {
        lblError.Text = "";
        lblUpdateStatus.Text = "";
        visiblePanels(true, false);
    }
    protected void datagrid_ItemCommand(object source, DataGridCommandEventArgs e)
    {
        try
        {
            if (e.CommandName == "cmdEdit")
            {
                ds.SelectCommandType = SqlDataSourceCommandType.Text;
                ds.SelectCommand = "SELECT MaAnChi.* FROM  MaAnChi where Ma=" + e.Item.Cells[0].Text;
                DataTable rs = ((DataView)ds.Select(System.Web.UI.DataSourceSelectArguments.Empty)).ToTable();

                this.txtId.Text = rs.Rows[0][0].ToString();
                txtMaAnChi.Text = rs.Rows[0]["MaAnChi"].ToString();
                this.txtTenAnChi.Text = rs.Rows[0]["TenAnChi"].ToString();
                this.txtTenNhom.Text = rs.Rows[0]["TenNhom"].ToString();
                this.cbAnChiMau.Checked = (rs.Rows[0]["AnChiMau"].ToString() == "True") ? true : false;
                this.chkXuatKH.Checked = (rs.Rows[0]["XuatKHTrongQLAC"].ToString() == "True") ? true : false;
                txtDonGia.Text = rs.Rows[0]["DonGia"].ToString();
                //txtMa_DonGia.Text = rs.Rows[0]["Ma_DonGia"].ToString();
                cboDotPhatHanh_edit.SelectedValue= rs.Rows[0]["MaDotPhatHanh"].ToString();
                try
                {
                    ddlMaLoaiAnChi.SelectedValue = rs.Rows[0]["MaLoaiAnChi"].ToString();
                }
                catch { }
                try
                {
                    cboDonViTinh.SelectedValue = rs.Rows[0]["DonViTinh"].ToString();
                }catch{}

                //for (int i = 0; i < ddlMaLoaiAnChi.Items.Count; i++)
                //{
                //    if (ddlMaLoaiAnChi.Items[i].Value.ToString() == rs.Rows[0]["MaLoaiAnChi"].ToString())
                //    {
                //        string s = rs.Rows[0]["MaLoaiAnChi"].ToString();
                //        ddlMaLoaiAnChi.SelectedIndex = i;
                //        break;
                //    }
                //}
                visiblePanels(false, true);

                this.lblError.Text = "";
                this.lblUpdateStatus.Text = "";
            }
            else if (e.CommandName == "cmdDelete")
            {
                // check existed maAnChi in KhoAnChi
                if (CheckExistedMaAnChi(e.Item.Cells[0].Text.Trim()))
                {
                    lblUpdateStatus.Attributes.Add("style", "color:red;font-weight:bold;");
                    this.lblUpdateStatus.Text = "Mã: " + e.Item.Cells[0].Text.Trim() + " đang được sử dụng. Bạn không thể xóa Ấn chỉ này được.";
                }
                else
                {
                    ds.DeleteCommand = "delete MaAnChi where Ma='" + e.Item.Cells[0].Text + "'";
                    ds.Delete();
                    datagrid.DataBind();
                }
            }
        }
        catch (SqlException ex)
        {
            lblUpdateStatus.Attributes.Add("style", "color:red;font-weight:bold;");
            this.lblUpdateStatus.Text = "Loi khi truy xuat du lieu. Nhap lai!";
        }
    }
    protected void datagrid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        if (e.Item.ItemIndex < 0) return;
        Button cmdDel = (Button)e.Item.FindControl("cmdDelete");
        if (cmdDel != null) cmdDel.Attributes.Add("onclick", TTQTCommon.delete_Confirm);
    }
    protected void datagrid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
    {
        datagrid.CurrentPageIndex = e.NewPageIndex;
        datagrid.DataBind();
    }
    private void FillDataToDDList(string ma)
    {
        try
        {
            ds.SelectCommandType = SqlDataSourceCommandType.Text;
            if (ma == null || ma == string.Empty)
            {
                ds.SelectCommand = "SELECT     MaLoaiAnChi, TenLoaiAnChi FROM MaLoaiAnChi";
            }
            else
            {
                ds.SelectCommand = "SELECT     MaLoaiAnChi, TenLoaiAnChi FROM MaLoaiAnChi"
                                      + " WHERE MaLoaiAnChi='" + ma + "'";
            }
            DataTable rsDDL = ((DataView)ds.Select(System.Web.UI.DataSourceSelectArguments.Empty)).ToTable();
            //ddlMaLoaiAnChi.DataSource = rsDDL;
            ddlMaLoaiAnChi.DataTextField = "TenLoaiAnChi";
            ddlMaLoaiAnChi.DataValueField = "MaLoaiAnChi";
            ddlMaLoaiAnChi.DataBind();
        }
        catch (SqlException ex)
        {
            lblUpdateStatus.Attributes.Add("style", "color:red;font-weight:bold;");
            this.lblUpdateStatus.Text = "Loi khi truy xuat du lieu. Nhap lai!";
        }
    }
    private bool CheckExistedMaAnChi(string maAC)
    {
        SqlConnection conn = new SqlConnection(TTQTCommon.DBConnectionString);
        SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM KhoAnChi WHERE Ma ='" + maAC + "'", conn);
        comm.CommandType = CommandType.Text;
        try
        {

            conn.Open();
            int count = Convert.ToInt32(comm.ExecuteScalar());
            conn.Close();
            comm.Dispose();

            return count > 0;
        }
        catch (Exception ex)
        {
            lblError.Text = "Lỗi khi kiểm tra tồn tại của Mã ấn chỉ \n" + ex.ToString();
            return false;
        }
    }
    protected void cboDotPhatHanh_SelectedIndexChanged(object sender, EventArgs e)
    {
        datagrid.DataBind();
    }
    protected void datagrid_PreRender(object sender, EventArgs e)
    {
        if(cboDotPhatHanh.SelectedValue.Equals("-1"))
        {
            datagrid.Columns[5].Visible = true;
        }
        else
        {
            datagrid.Columns[5].Visible = false;
        }
    }
}
